import cv2
import numpy as np
from deepface import DeepFace
from fastapi import APIRouter, UploadFile, File, Depends

from database import get_db
from services.face_db import FaceDBService
from sqlalchemy.orm import Session

router2 = APIRouter()


@router2.post("/api/recognize")
async def recognize_face(
        file: UploadFile = File(...),
        threshold: float = 0.7,
        db: Session = Depends(get_db)
):
    # 读取并处理图片
    contents = await file.read()
    nparr = np.frombuffer(contents, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    # 将BGR转换为RGB
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # 特征提取
    try:
        embedding_obj = DeepFace.represent(
            img,
            model_name='Facenet',
            enforce_detection=True
        )
    except ValueError:
        return {"matches": []}

    # 数据库搜索
    service = FaceDBService(db)
    results = service.search_face(
        embedding_obj[0]['embedding'],
        threshold=threshold
    )

    return {"matches": results}